#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>

const char* menu[] =
{
	"a - add new record",
	"d - delete record",
	"q - quit",
	NULL
};

int getchoice(const char* greet, const char* choices[], FILE* In, FILE* out);

int main(void)
{
	int choice = 0;
	FILE* input;
	FILE* output;

	if (!isatty(fileno(stdout)))
	{
		fprintf(stderr, "You are not a termnial!\n");
	}

	input = fopen("/dev/tty", "r");
	output = fopen("/dev/tty", "w");
	if (NULL == input || NULL == output)
	{
		fprintf(stderr, "Unable to open /dev/tty\n");
		return 1;
	}

	do
	{
		choice = getchoice("Please select an action", menu, input, output);
		printf ("You have chose: %c\n", choice);
	}while (choice != 'q');

	return 0;
}

int getchoice(const char* greet, const char* choices[], FILE* in, FILE* out)
{
	int chosen = 0;
	int selected;
	const char** option;

	do
	{
		fprintf (out, "Choice: %s\n", greet);
		option = choices;
		while (NULL != *option)
		{
			fprintf (out, "%s\n", *option);
			option++;
		}

		do
		{
			selected = fgetc(in);
		}while ('\n' == selected);

		option = choices;
		while (NULL != *option)
		{
			if (selected == *option[0])
			{
				chosen = 1;
				break;
			}
			option++;
		}
		if (0 == chosen)
		{
			fprintf (out, "Incorrect choice, select again\n");
		}
	}while (0 == chosen);

	return selected;
}
